package cn.sskxyz.security.authorization.config;

import cn.sskxyz.security.core.config.NimbusJwtDecoder;
import cn.sskxyz.security.core.property.SecurityProperties;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
@EnableConfigurationProperties(SecurityProperties.class)
public class WebSecurityConfigure extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityProperties securityProperties;

    // 认证服务同时做资源服务时，配置该项
//    @Autowired
//    private JWKSet jwkSet;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

             http.formLogin()
                    .loginPage(securityProperties.getLoginPage())
                     .loginProcessingUrl(securityProperties.getFormAction()).permitAll()
//                    .failureHandler(new SessionFailureHandler())
                .and()
                    .logout()
                    .logoutUrl(securityProperties.getLogoutAction()).clearAuthentication(true)
                    .logoutSuccessUrl(securityProperties.getExitPage()).permitAll()
                .and()
                    .authorizeRequests()
                    .antMatchers("/.well-known/jwks.json").permitAll()
                    .antMatchers("/permission","/service").permitAll()
                    .antMatchers("/oauth/**").authenticated()
                    .anyRequest().authenticated()
//                .and()
//                     .oauth2ResourceServer()
//                     .jwt()
//                     .decoder(new NimbusJwtDecoder(new ImmutableJWKSet(jwkSet)))
//                .and()
                .and()
                    .sessionManagement()
                .and()
                    .cors().configurationSource(new AllowAllCorsConfigure())
                .and()
                    .csrf().disable();
    }

    /**
     * 用于支持密码模式认证
     * @return
     * @throws Exception
     */
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
